/**
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 */
package com.jeesite.modules.financing.web.finserviceorder;

import com.jeesite.common.collect.ListUtils;
import com.jeesite.common.config.Global;
import com.jeesite.common.entity.Page;
import com.jeesite.common.lang.DateUtils;
import com.jeesite.common.lang.NumberUtils;
import com.jeesite.common.web.BaseController;
import com.jeesite.modules.ar.dao.TarDetailDao;
import com.jeesite.modules.ar.entity.Tar;
import com.jeesite.modules.ar.entity.TarDetail;
import com.jeesite.modules.ar.service.TarService;
import com.jeesite.modules.base.entity.cars.Tcar;
import com.jeesite.modules.base.entity.customer.Customer;
import com.jeesite.modules.base.entity.fixedexpense.FixedExpense;
import com.jeesite.modules.base.entity.investorfinancialinfo.InvestorFinancialInfo;
import com.jeesite.modules.base.entity.investorfinancialinfo.PadTaxInterest;
import com.jeesite.modules.base.entity.supplier.Supplier;
import com.jeesite.modules.base.entity.warehouse.Twarehouse;
import com.jeesite.modules.base.service.customer.CustomerService;
import com.jeesite.modules.base.service.fixedexpense.FixedExpenseService;
import com.jeesite.modules.base.service.investorfinancialinfo.InvestorFinancialInfoService;
import com.jeesite.modules.base.service.supplier.SupplierService;
import com.jeesite.modules.base.service.warehouse.TwarehouseService;
import com.jeesite.modules.custom.enumInfo.AccountType;
import com.jeesite.modules.custom.enumInfo.BillStatusEnum;
import com.jeesite.modules.custom.enumInfo.supplierTypeEnum;
import com.jeesite.modules.financing.dao.finserviceorder.FinServiceOrderDao;
import com.jeesite.modules.financing.entity.finserviceorder.FinServiceOrder;
import com.jeesite.modules.financing.entity.finserviceorder.FinancialRecords;
import com.jeesite.modules.financing.entity.finserviceorder.TfinancingServiceOrderDetail;
import com.jeesite.modules.financing.service.finserviceorder.FinServiceOrderService;
import com.jeesite.modules.order.dao.serviceorder.ServiceOrderDetailDao;
import com.jeesite.modules.order.entity.serviceorder.ServiceOrder;
import com.jeesite.modules.order.entity.serviceorder.ServiceOrderDetail;
import com.jeesite.modules.order.service.serviceorder.ServiceOrderService;
import com.jeesite.modules.payment.dao.TapDetailDao;
import com.jeesite.modules.payment.entity.Tap;
import com.jeesite.modules.payment.entity.TapDetail;
import com.jeesite.modules.payment.service.TapService;
import com.jeesite.modules.prepay.entity.Tprepayment;
import com.jeesite.modules.prepay.entity.TprepaymentEstimated;
import com.jeesite.modules.prepay.service.TprepaymentService;
import com.jeesite.modules.prerecieve.entity.TadvancesReceived;
import com.jeesite.modules.prerecieve.entity.TadvancesReceivedEstimated;
import com.jeesite.modules.prerecieve.service.TadvancesReceivedService;
import com.jeesite.modules.sys.entity.Company;
import com.jeesite.modules.sys.entity.EmpUser;
import com.jeesite.modules.sys.entity.Employee;
import com.jeesite.modules.sys.service.CompanyService;
import com.jeesite.modules.sys.service.EmpUserService;
import com.jeesite.modules.sys.utils.DictUtils;
import com.jeesite.modules.sys.utils.EmpUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 融资服务订单Controller
 * @author YY
 * @version 2021-03-16
 */
@Controller
@RequestMapping(value = "${adminPath}/financing/finserviceorder/finServiceOrder")
public class FinServiceOrderController extends BaseController {

	@Autowired
	private FinServiceOrderService finServiceOrderService;
	@Autowired
	private FinServiceOrderDao finServiceOrderDao;
	@Autowired
	private CustomerService customerService;
	@Autowired
	private ServiceOrderDetailDao serviceOrderDetailDao;
	@Autowired
	private SupplierService supplierService;
	@Autowired
	private TwarehouseService twarehouseService;
    @Autowired
    private InvestorFinancialInfoService investorFinancialInfoService;
    @Autowired
    private ServiceOrderService serviceOrderService;
    @Autowired
    private TarService tarService;
    @Autowired
    private TarDetailDao tarDetailDao;
    @Autowired
    private TapService tapService;
    @Autowired
    private TapDetailDao tapDetailDao;
    @Autowired
    private TadvancesReceivedService tadvancesReceivedService;
    @Autowired
    private TprepaymentService tprepaymentService;
    @Autowired
    private FixedExpenseService fixedExpenseService;
    @Autowired
    private EmpUserService empUserService;
    @Autowired
    private CompanyService companyService;

    /**
     * 获取数据
     */
    @ModelAttribute
    public FinServiceOrder get(String financingServiceOrderId, boolean isNewRecord) {
        return finServiceOrderService.get(financingServiceOrderId, isNewRecord);
    }

    /**
     * 查询列表
     */
    @RequiresPermissions("financing:finserviceorder:finServiceOrder:view")
    @RequestMapping(value = {"list", ""})
    public String list(FinServiceOrder finServiceOrder, Model model) {
        List < Customer > list = customerService.findList(new Customer());
        model.addAttribute("customerList", list);//客户列表

        Supplier supplier = new Supplier();
        supplier.setSupplierType(supplierTypeEnum.IN_SUPPLIER.getCode());// 国内资方
        List < Supplier > list1 = supplierService.findList(supplier);
        model.addAttribute("supplierList", list1);//国内资方（供应商类型为一的）列表

        List < Twarehouse > list2 = twarehouseService.findList(new Twarehouse());
        model.addAttribute("twarehouseList", list2);//融资地点（仓库）列表

        model.addAttribute("listUser", empUserService.findList(new EmpUser()));
        model.addAttribute("finServiceOrder", finServiceOrder);
        return "modules/financing/finserviceorder/finServiceOrderList";
    }

    /**
     * 查询列表数据
     */
    @RequiresPermissions("financing:finserviceorder:finServiceOrder:view")
    @RequestMapping(value = "listData")
    @ResponseBody
    public Page < FinServiceOrder > listData(FinServiceOrder finServiceOrder, HttpServletRequest request, HttpServletResponse response) {
        finServiceOrder.setPage(new Page <>(request, response));
        Page < FinServiceOrder > page = finServiceOrderService.findPage(finServiceOrder);
        return page;
    }


    /**
     * 查看编辑表单
     */
    @RequiresPermissions("financing:finserviceorder:finServiceOrder:view")
    @RequestMapping(value = "form")
    public String form(FinServiceOrder finServiceOrder, Model model) {
        if (finServiceOrder.getIsNewRecord()) {
            finServiceOrder.setRecordStatus("1"); // 有效
            model.addAttribute("listFrameNumber", ListUtils.newArrayList());
            model.addAttribute("listGroupName", ListUtils.newArrayList());
        } else {
            model.addAttribute("listFrameNumber", getFramenumber(finServiceOrder.getCustomerId()));
            model.addAttribute("listGroupName", getTaxNameByInvestorName(finServiceOrder.getInvestorId(),finServiceOrder.getFinancingMethod()));
        }
        List < TfinancingServiceOrderDetail > tfinancingServiceOrderDetailList = finServiceOrder.getTfinancingServiceOrderDetailList();
        List < TfinancingServiceOrderDetail > collect1 = tfinancingServiceOrderDetailList.stream().filter(ele -> "1".equals(ele.getType())).collect(Collectors.toList());
        List < TfinancingServiceOrderDetail > collect2 = tfinancingServiceOrderDetailList.stream().filter(ele -> "2".equals(ele.getType())).collect(Collectors.toList());
        finServiceOrder.setTfinancingServiceOrderDetailList1(collect1);//资方税率方案列表
        finServiceOrder.setTfinancingServiceOrderDetailList2(collect2);//客户税率方案列表

        List < Customer > list = customerService.findList(new Customer());
        model.addAttribute("customerList", list);//客户列表

        Supplier supplier = new Supplier();
        supplier.setSupplierType(supplierTypeEnum.IN_SUPPLIER.getCode());
        List < Supplier > list1 = supplierService.findList(supplier);
        model.addAttribute("supplierList", list1);//国内资方（供应商类型为一的）列表

        List < Twarehouse > list2 = twarehouseService.findList(new Twarehouse());
        model.addAttribute("twarehouseList", list2);//融资地点（仓库）列表
        model.addAttribute("companyList", companyService.findList(new Company()));
        model.addAttribute("finServiceOrder", finServiceOrder);
        return "modules/financing/finserviceorder/finServiceOrderForm";
    }

    /**
     * 查看表单详情
     */
    @RequiresPermissions("financing:finserviceorder:finServiceOrder:view")
    @RequestMapping(value = "detail")
    public String detail(FinServiceOrder finServiceOrder, Model model) {
        List < Customer > list = customerService.findList(new Customer());
        model.addAttribute("customerList", list);//客户列表
        model.addAttribute("listFrameNumber", getFramenumber(finServiceOrder.getCustomerId()));
        model.addAttribute("listGroupName", getTaxNameByInvestorName(finServiceOrder.getInvestorId(),finServiceOrder.getFinancingMethod()));
        List < Twarehouse > list2 = twarehouseService.findList(new Twarehouse());
        model.addAttribute("twarehouseList", list2);//融资地点（仓库）列表
        model.addAttribute("companyList", companyService.findList(new Company()));
        Supplier supplier = new Supplier();
        supplier.setSupplierType(supplierTypeEnum.IN_SUPPLIER.getCode());// 国内资方
        List < Supplier > list1 = supplierService.findList(supplier);
        model.addAttribute("supplierList", list1);//国内资方（供应商类型为一的）列表

        Double investorInterestTotal = 0D;//资方利息合计
        Double customerInterestTotal = 0D;//客户利息合计
        List < TfinancingServiceOrderDetail > tfinancingServiceOrderDetailList = finServiceOrder.getTfinancingServiceOrderDetailList();
        List < TfinancingServiceOrderDetail > tfinancingServiceOrderDetailList1 = ListUtils.newArrayList();
        List < TfinancingServiceOrderDetail > tfinancingServiceOrderDetailList2 = ListUtils.newArrayList();
        InvestorFinancialInfo investorFinancialInfo = new InvestorFinancialInfo();
        investorFinancialInfo.setInvestorName(finServiceOrder.getInvestorId());
        InvestorFinancialInfo investorFinancialInfo1 = investorFinancialInfoService.get(investorFinancialInfoService.findList(investorFinancialInfo).get(0));
        Long investorYearDays = investorFinancialInfo1.getDays();
        for (TfinancingServiceOrderDetail Detail : tfinancingServiceOrderDetailList) {
            if ("1".equals(Detail.getType())) {
                Double investorDetailDays = 0D;  //发生天数
                Double investorDetailRatio = NumberUtils.div(Double.parseDouble(Detail.getInterestRate()), 100); //资方利率
                Double negotiatedAmount1 = finServiceOrder.getCarTotalAmount();
                if (new Date().compareTo(Detail.getStartDate()) >= 0 && new Date().compareTo(Detail.getEndDate()) <= 0) {
                    investorDetailDays = DateUtils.getDistanceOfTwoDate(Detail.getStartDate(), new Date());
                } else if (new Date().compareTo(Detail.getStartDate()) > 0 && new Date().compareTo(Detail.getEndDate()) > 0) {
                    investorDetailDays = DateUtils.getDistanceOfTwoDate(Detail.getStartDate(), Detail.getEndDate());
                }
                if ("2".equals(finServiceOrder.getCalculationMethod()))// 本金加上期利息
                {
                    negotiatedAmount1 = negotiatedAmount1 + investorInterestTotal;
                }
                //针对
                Double interest = NumberUtils.mul(NumberUtils.div(NumberUtils.mul(negotiatedAmount1, investorDetailRatio), investorYearDays), investorDetailDays);
                investorInterestTotal = NumberUtils.add(investorInterestTotal, interest);
                Detail.setInterest(Double.valueOf(String.format("%.2f", interest)));
                tfinancingServiceOrderDetailList1.add(Detail);
            } else if ("2".equals(Detail.getType())) {
                Double investorDetailDays = 0D;  //发生天数
                Double investorDetailRatio = NumberUtils.div(Double.parseDouble(Detail.getInterestRate()), 100); //利率
                Double negotiatedAmount2 = finServiceOrder.getCarTotalAmount();
                if (new Date().compareTo(Detail.getStartDate()) >= 0 && new Date().compareTo(Detail.getEndDate()) <= 0) {
                    investorDetailDays = DateUtils.getDistanceOfTwoDate(Detail.getStartDate(), new Date());
                } else if (new Date().compareTo(Detail.getStartDate()) > 0 && new Date().compareTo(Detail.getEndDate()) > 0) {
                    investorDetailDays = DateUtils.getDistanceOfTwoDate(Detail.getStartDate(), Detail.getEndDate());
                }
                if ("2".equals(finServiceOrder.getCalculationMethod()))// 本金加上期利息
                {
                    negotiatedAmount2 = negotiatedAmount2 + customerInterestTotal;
                }
                Double interest = NumberUtils.mul(NumberUtils.div(NumberUtils.mul(negotiatedAmount2, investorDetailRatio), investorYearDays), investorDetailDays);
                customerInterestTotal = NumberUtils.add(customerInterestTotal, interest);
                Detail.setInterest(Double.valueOf(String.format("%.2f", interest)));
                tfinancingServiceOrderDetailList2.add(Detail);
            }
        }
        List < FinancialRecords > tarList = ListUtils.newArrayList();//应收相关财务记录
        List < FinancialRecords > tapList = ListUtils.newArrayList();//应付相关财务记录
        List < FinancialRecords > adList = ListUtils.newArrayList();//预收相关财务记录
        List < FinancialRecords > preList = ListUtils.newArrayList();//预付相关财务记录
        Tar tar = new Tar();
        tar.setParentBillCode(finServiceOrder.getFinancingServiceOrderId());
        List < Tar > tarlist1 = tarService.findList(tar);
        for (Tar tar1 : tarlist1) {
            Tar tar2 = tarService.get(tar1);
            for (TarDetail tarDetail : tar2.getTarDetailList()) {
                FinancialRecords financialRecords = new FinancialRecords();
                financialRecords.setBillID(tar2.getArId());
                financialRecords.setBillCode(tar2.getArCode());
                financialRecords.setBillType("tar001");
                financialRecords.setDate(tar2.getDate());
                FixedExpense fixedExpense = fixedExpenseService.get(new FixedExpense(tarDetail.getExpenseItem()));
                financialRecords.setExpenseItem(fixedExpense.getFixedExpenseName());
                financialRecords.setApAmount(tarDetail.getApAmount());
                financialRecords.setStatus1(tar2.getStatus1());
                tarList.add(financialRecords);
            }
        }

        Tap tap = new Tap();
        tap.setParentBillCode(finServiceOrder.getFinancingServiceOrderId());
        List < Tap > taplist1 = tapService.findList(tap);
        for (Tap tap1 : taplist1) {
            Tap tap2 = tapService.get(tap1);
            for (TapDetail tapDetail : tap2.getTapDetailList()) {
                FinancialRecords financialRecords = new FinancialRecords();
                financialRecords.setBillID(tap2.getApId());
                financialRecords.setBillCode(tap2.getApCode());
                financialRecords.setBillType("investorcarcontract001");
                financialRecords.setDate(tap2.getDate());
                FixedExpense fixedExpense = fixedExpenseService.get(new FixedExpense(tapDetail.getExpenseItem()));
                financialRecords.setExpenseItem(fixedExpense.getFixedExpenseName());
                financialRecords.setApAmount(tapDetail.getApAmount());
                financialRecords.setStatus1(tap2.getStatus1());
                tapList.add(financialRecords);
            }
        }

        TadvancesReceived tadvancesReceived = new TadvancesReceived();
        tadvancesReceived.setParentBillCode(finServiceOrder.getFinancingServiceOrderId());
        List < TadvancesReceived > adlist1 = tadvancesReceivedService.findList(tadvancesReceived);
        for (TadvancesReceived received : adlist1) {
            TadvancesReceived tadvancesReceived1 = tadvancesReceivedService.get(received);
            FinancialRecords financialRecords = new FinancialRecords();
            financialRecords.setBillID(tadvancesReceived1.getAdvancesReceivedId());
            financialRecords.setBillCode(tadvancesReceived1.getAdvancesReceivedCode());
            financialRecords.setBillType("releasecar002");
            financialRecords.setDate(tadvancesReceived1.getDate());
            FixedExpense fixedExpense = fixedExpenseService.get(tadvancesReceived1.getTadvancesReceivedEstimatedList().get(0).getAdvancesReceivedType());
            financialRecords.setExpenseItem(fixedExpense.getFixedExpenseName());
            financialRecords.setApAmount(tadvancesReceived1.getTadvancesReceivedEstimatedList().get(0).getEstimatedReceivedAmount());
            financialRecords.setStatus1(received.getStatus1());
            tapList.add(financialRecords);
        }
        Tprepayment tprepayment = new Tprepayment();
        tprepayment.setParentBillCode(finServiceOrder.getFinancingServiceOrderId());
        List < Tprepayment > prlist1 = tprepaymentService.findList(tprepayment);
        for (Tprepayment tprepayment1 : prlist1) {
            Tprepayment tprepayment2 = tprepaymentService.get(tprepayment1);
            FinancialRecords financialRecords = new FinancialRecords();
            financialRecords.setBillID(tprepayment2.getPrepaymentId());
            financialRecords.setBillCode(tprepayment2.getPrepaymentCode());
            financialRecords.setBillType("inboundorder001");
            financialRecords.setDate(tprepayment2.getDate());
            FixedExpense fixedExpense = fixedExpenseService.get(tprepayment2.getTprepaymentEstimatedList().get(0).getPrepaymentType());
            financialRecords.setExpenseItem(fixedExpense.getFixedExpenseName());
            financialRecords.setApAmount(tprepayment2.getTprepaymentEstimatedList().get(0).getEstimatedPaymentAmount());
            financialRecords.setStatus1(tprepayment2.getStatus1());
            tapList.add(financialRecords);
        }

        finServiceOrder.getFinancialRecordsList().addAll(tarList);
        finServiceOrder.getFinancialRecordsList().addAll(tapList);
        finServiceOrder.getFinancialRecordsList().addAll(adList);
        finServiceOrder.getFinancialRecordsList().addAll(preList);
        finServiceOrder.setTfinancingServiceOrderDetailList1(tfinancingServiceOrderDetailList1);
        finServiceOrder.setTfinancingServiceOrderDetailList2(tfinancingServiceOrderDetailList2);
        model.addAttribute("finServiceOrder", finServiceOrder);
        return "modules/financing/finserviceorder/finServiceOrderDetail";
    }

    /**
     * 保存数据
     */
    @RequiresPermissions("financing:finserviceorder:finServiceOrder:edit")
    @PostMapping(value = "save")
    @ResponseBody
    public String save(@Validated FinServiceOrder finServiceOrder) {
        List < TfinancingServiceOrderDetail > detailList1 = finServiceOrder.getTfinancingServiceOrderDetailList1();
        for (int i = 0; i < detailList1.size(); i++) {
            detailList1.get(i).setRowNumber(i + 1);
        }
        List < TfinancingServiceOrderDetail > detailList2 = finServiceOrder.getTfinancingServiceOrderDetailList2();
        for (int i = 0; i < detailList2.size(); i++) {
            detailList2.get(i).setRowNumber(i + 1);
        }
        List < TfinancingServiceOrderDetail > list = ListUtils.newArrayList();
        list.addAll(detailList1);
        list.addAll(detailList2);
        finServiceOrder.setTfinancingServiceOrderDetailList(list);
        finServiceOrderService.save(finServiceOrder);
        return renderResult(Global.TRUE, text("保存融资服务订单成功！"));
    }

    /**
     * 删除数据
     */
    @RequiresPermissions("financing:finserviceorder:finServiceOrder:edit")
    @RequestMapping(value = "delete")
    @ResponseBody
    public String delete(FinServiceOrder finServiceOrder) {
        finServiceOrderService.delete(finServiceOrder);
        return renderResult(Global.TRUE, text("删除融资服务订单成功！"));
    }

    /**
     * @param cusId 客户id
     */
    @RequestMapping(value = "getFramenumber")
    @ResponseBody
    public List < String > getFramenumber(@RequestParam("customerId") String cusId) {
        List < String > strings = finServiceOrderDao.selectFramenumber(cusId);
        return strings;
    }

    /**
     * 通过车架号，得到车牌等信息
     *
     * @param frameNumber 订单号id
     */
    @RequestMapping(value = "getDetailByFramenumber")
    @ResponseBody
    public ServiceOrderDetail getDetailByFramenumber(@RequestParam("frameNumber") String frameNumber) {
        ServiceOrderDetail serviceOrderDetail = new ServiceOrderDetail();
        serviceOrderDetail.setFrameNumber(frameNumber);
        List < ServiceOrderDetail > list = serviceOrderDetailDao.findList(serviceOrderDetail);
        return list.get(0);
    }

    /**
     * 获得当前用户的公司名
     */
    @RequestMapping(value = "getCompanyName")
    @ResponseBody
    public String getCompanyName() {
        Employee employee = EmpUtils.getEmployee();
        return employee.getCompany().getCompanyName();
    }

    /**
     * 获得税率方案
     *
     * @param
     */
    @RequestMapping(value = "getTaxByinvestorName")
    @ResponseBody
    public InvestorFinancialInfo selectTaxByinvestorName(@RequestParam("investorName") String investorName,
                                                         @RequestParam("financingMethod") String financingMethod,
                                                         @RequestParam("groupName") String groupName) {
        String financing_method = DictUtils.getDictLabel("financing_method", financingMethod, "1");
//		List<PadTaxInterest> padTaxInterests = finServiceOrderDao.selectTaxByinvestorName(investorName, financing_method);
//		if(padTaxInterests.size()!=0) {
//			InvestorFinancialInfo investorFinancialInfo = finServiceOrderDao.selectFinancialByInvestorId(investorName);
//			padTaxInterests.get(0).setInvestorFinancialInfoId(investorFinancialInfo);
//			return padTaxInterests;
//		}
        InvestorFinancialInfo investorFinancialInfo = new InvestorFinancialInfo();
        investorFinancialInfo.setInvestorName(investorName);//卡资方
        investorFinancialInfo.setFinancingMethod(financingMethod);//卡融资方法（展融扩容）
        investorFinancialInfo.setGroupName(groupName);//卡组合名称
        investorFinancialInfo.setFinancingType("4");//卡单据类型
        InvestorFinancialInfo investorFinancialInfo1 = investorFinancialInfoService.get(investorFinancialInfoService.findList(investorFinancialInfo).get(0));
        for (PadTaxInterest padTaxInterest : investorFinancialInfo1.getPadTaxInterestList()) {
            if ("1".equals(padTaxInterest.getStageType()))//资方垫税方案
            {
                investorFinancialInfo1.getPadTaxInterestList3().add(padTaxInterest);
            } else if ("2".equals(padTaxInterest.getStageType())) {
                investorFinancialInfo1.getPadTaxInterestList4().add(padTaxInterest);
            }
        }
        return investorFinancialInfo1;
    }

    /**
     * 客户还款按钮跳转页面
     * *@param
     */
    @RequiresPermissions("financing:finserviceorder:finServiceOrder:edit")
    @RequestMapping(value = "finCuREFrom")
    public String finCuREFrom(FinServiceOrder finServiceOrder, Model model) {
        model.addAttribute("finServiceOrder", finServiceOrder);
        return "modules/financing/finserviceorder/finCustomerRemittanceForm";
    }

    /**
     * 还款到资方按钮跳转页面
     * *@param
     */
    @RequiresPermissions("financing:finserviceorder:finServiceOrder:edit")
    @RequestMapping(value = "finInREFrom")
    public String finInREFrom(FinServiceOrder finServiceOrder, Model model) {
        model.addAttribute("finServiceOrder", finServiceOrder);
        return "modules/financing/finserviceorder/finInvestorRemittanceForm";
    }

    /**
     * 保证预收跳转页面
     * *@param
     */
    @RequiresPermissions("financing:finserviceorder:finServiceOrder:edit")
    @RequestMapping(value = "finAdFrom")
    public String finAdFrom(FinServiceOrder finServiceOrder,
                            @RequestParam("money") Double money,
                            @RequestParam("rowId") String rowId,
                            Model model) {
        finServiceOrder.setMoney(money);
        finServiceOrder.setGridRowId(rowId);
        model.addAttribute("finServiceOrder", finServiceOrder);
        return "modules/financing/finserviceorder/finAdvancesReceivedForm";
    }

    /**
     * 保证预付跳转页面
     * *@param
     */
    @RequiresPermissions("financing:finserviceorder:finServiceOrder:edit")
    @RequestMapping(value = "finPreFrom")
    public String finPreFrom(FinServiceOrder finServiceOrder,
                             @RequestParam("money") Double money,
                             @RequestParam("rowId") String rowId,
                             Model model) {
        finServiceOrder.setMoney(money);
        finServiceOrder.setGridRowId(rowId);
        model.addAttribute("finServiceOrder", finServiceOrder);
        return "modules/financing/finserviceorder/finPrePaymentReceivedForm";
    }

    /**
     * 客户还款
     */
    @RequiresPermissions("financial:billnegotiated:billNegotiated:edit")
    @PostMapping(value = "saveFinCuREFrom")
    @ResponseBody
    @Transactional(readOnly = false)
    public String saveFinCuREFrom(FinServiceOrder finServiceOrder) {
//		TadvancesReceived
        FinServiceOrder finServiceOrder1 = finServiceOrder;
        List < TfinancingServiceOrderDetail > tfinancingServiceOrderDetailList = finServiceOrder.getTfinancingServiceOrderDetailList();
        TfinancingServiceOrderDetail tfinancingServiceOrderDetail = tfinancingServiceOrderDetailList.stream().filter(ele -> "2".equals(ele.getType()) && ele.getStartDays() == 0).findFirst().get();//客户详情第一条
        long distanceOfTwoDate = (long) DateUtils.getDistanceOfTwoDate(tfinancingServiceOrderDetail.getStartDate(), finServiceOrder.getCustomerRepaymentDate());
        Date day = finServiceOrder.getCustomerRepaymentDate();//客户自己选的实际还款日期
//		Double investorInterestTotal = 0D;//资方利息合计
        Double customerInterestTotal = 0D;//客户利息合计
        InvestorFinancialInfo investorFinancialInfo = new InvestorFinancialInfo();
        investorFinancialInfo.setInvestorName(finServiceOrder.getInvestorId());
        InvestorFinancialInfo investorFinancialInfo1 = investorFinancialInfoService.get(investorFinancialInfoService.findList(investorFinancialInfo).get(0));
        Long investorYearDays = investorFinancialInfo1.getDays();//资方年天数
        for (TfinancingServiceOrderDetail Detail : tfinancingServiceOrderDetailList) {
            if ("2".equals(Detail.getType())) {
                Double investorDetailDays = 0D;  //发生天数
                Double investorDetailRatio = NumberUtils.div(Double.parseDouble(Detail.getInterestRate()), 100); //利率
                Double negotiatedAmount2 = finServiceOrder.getCarTotalAmount();
                if (day.compareTo(Detail.getStartDate()) >= 0 && day.compareTo(Detail.getEndDate()) <= 0) {
                    investorDetailDays = DateUtils.getDistanceOfTwoDate(Detail.getStartDate(), day);
                } else if (day.compareTo(Detail.getStartDate()) > 0 && day.compareTo(Detail.getEndDate()) > 0) {
                    investorDetailDays = DateUtils.getDistanceOfTwoDate(Detail.getStartDate(), Detail.getEndDate());
                }
                if ("2".equals(finServiceOrder.getCalculationMethod()))// 本金加上期利息
                {
                    negotiatedAmount2 = negotiatedAmount2 + customerInterestTotal;
                }
                Double interest = NumberUtils.mul(NumberUtils.div(NumberUtils.mul(negotiatedAmount2, investorDetailRatio), investorYearDays), investorDetailDays);
                customerInterestTotal = NumberUtils.add(customerInterestTotal, interest);
                Detail.setInterest(Double.valueOf(String.format("%.2f", interest)));
            }
        }
        Double totalDays = DateUtils.getDistanceOfTwoDate(tfinancingServiceOrderDetailList.get(0).getStartDate(), day);//合计天数
        finServiceOrder.setCustomerRepaymentDate(day);
        finServiceOrder.setCustomerDays(totalDays.longValue());
        finServiceOrder.setCustomerTotalInterest(Double.valueOf(String.format("%.2f", customerInterestTotal)));
        finServiceOrder.setCustomerTotalPrincipalInterest(Double.valueOf(String.format("%.2f", NumberUtils.add(customerInterestTotal, finServiceOrder.getCarTotalAmount()))));
        //生成财务相关记录

        finServiceOrderService.save(finServiceOrder);//更新客户还款信息
        //获得币种
        ServiceOrderDetail serviceOrderDetail = new ServiceOrderDetail();
        serviceOrderDetail.setFrameNumber(finServiceOrder.getFrameNumber());
        ServiceOrderDetail serviceOrderDetail1 = serviceOrderDetailDao.findList(serviceOrderDetail).get(0);
        //获得了车架号对应的订单
        ServiceOrder serviceOrder = serviceOrderService.get(new ServiceOrder(serviceOrderDetail1.getServiceOrderId().getServiceOrderId()));
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Tar tar = new Tar();
        tar.setCustomerId(finServiceOrder.getCustomer().getCustomerId());
        tar.setCustomer(finServiceOrder.getCustomer());//客户
        tar.setDate(new Date());//日期
        tar.setStatus1("1"); //默认待生效
        tar.setServiceOrderId(serviceOrder.getServiceOrderId());
        tar.setServiceOrder(serviceOrder);
        tar.setCurrency(serviceOrder.getCurrency());//币种
        tar.setAmount(NumberUtils.add(finServiceOrder.getCarTotalAmount(), Double.valueOf(String.format("%.2f", customerInterestTotal))));
        tar.setParentBillType("finServiceOrder001");
        tar.setParentBillCode(finServiceOrder.getFinancingServiceOrderId());
        tar.setRemarks(finServiceOrder.getRemarks());

        //生成字表
        List < TarDetail > tarDetailList = ListUtils.newArrayList();
        for (int i = 0; i < 2; i++) {
            TarDetail tarDetail = new TarDetail();
            tarDetail.setBrand(serviceOrderDetail1.getBrand());
            tarDetail.setArea(serviceOrderDetail1.getArea());
            tarDetail.setModel(serviceOrderDetail1.getModel());
            tarDetail.setFrameNumber(serviceOrderDetail1.getFrameNumber());
            tarDetail.setCarId(serviceOrderDetail1.getCarId());
            tarDetail.setCar(new Tcar(serviceOrderDetail1.getCarId()));
            tarDetail.setRowNumber(serviceOrderDetail1.getRowNumber());
            if (i == 0) {
                if ("1".equals(finServiceOrder.getFinancingMethod())) {
                    tarDetail.setExpenseItem(AccountType.ZRBJ.getCode());
                    tarDetail.setFixedExpense(new FixedExpense(AccountType.ZRBJ.getCode()));
                } else if ("2".equals(finServiceOrder.getFinancingMethod())) {
                    tarDetail.setExpenseItem(AccountType.KRBJ.getCode());
                    tarDetail.setFixedExpense(new FixedExpense(AccountType.KRBJ.getCode()));
                }
                tarDetail.setApAmount(finServiceOrder.getCarTotalAmount());
            } else if (i == 1) {
                if ("1".equals(finServiceOrder.getFinancingMethod())) {
                    tarDetail.setExpenseItem(AccountType.ZRLX.getCode());
                    tarDetail.setFixedExpense(new FixedExpense(AccountType.ZRLX.getCode()));
                } else if ("2".equals(finServiceOrder.getFinancingMethod())) {
                    tarDetail.setExpenseItem(AccountType.KRLX.getCode());
                    tarDetail.setFixedExpense(new FixedExpense(AccountType.KRLX.getCode()));
                }
                tarDetail.setApAmount(Double.valueOf(String.format("%.2f", customerInterestTotal)));
            }
            tarDetailList.add(tarDetail);
        }
        tar.setTarDetailList(tarDetailList);
        tarService.save(tar);
        // todo 生成客户应收
        return renderResult(Global.TRUE, text("客户还汇保存成功！"));
    }

    /**
     * 还款到资方
     */
    @RequiresPermissions("financial:billnegotiated:billNegotiated:edit")
    @PostMapping(value = "saveFinInREFrom")
    @ResponseBody
    @Transactional(readOnly = false)
    public String saveFinInREFrom(FinServiceOrder finServiceOrder) {
        FinServiceOrder finServiceOrder1 = finServiceOrder;
        List < TfinancingServiceOrderDetail > tfinancingServiceOrderDetailList = finServiceOrder.getTfinancingServiceOrderDetailList();
        TfinancingServiceOrderDetail tfinancingServiceOrderDetail = tfinancingServiceOrderDetailList.stream().filter(ele -> "1".equals(ele.getType()) && ele.getStartDays() == 0).findFirst().get();//资方详情第一条
        long distanceOfTwoDate = (long) DateUtils.getDistanceOfTwoDate(tfinancingServiceOrderDetail.getStartDate(), finServiceOrder.getInvestorRepaymentDate());
        Date day = finServiceOrder.getInvestorRepaymentDate();//资方自己选的实际还款日期
        Double customerInterestTotal = 0D;//资方利息合计
        InvestorFinancialInfo investorFinancialInfo = new InvestorFinancialInfo();
        investorFinancialInfo.setInvestorName(finServiceOrder.getInvestorId());
        InvestorFinancialInfo investorFinancialInfo1 = investorFinancialInfoService.get(investorFinancialInfoService.findList(investorFinancialInfo).get(0));
        Long investorYearDays = investorFinancialInfo1.getDays();//资方年天数
        for (TfinancingServiceOrderDetail Detail : tfinancingServiceOrderDetailList) {
            if ("1".equals(Detail.getType())) {
                Double investorDetailDays = 0D;  //发生天数
                Double investorDetailRatio = NumberUtils.div(Double.parseDouble(Detail.getInterestRate()), 100); //利率
                Double negotiatedAmount2 = finServiceOrder.getCarTotalAmount();
                if (day.compareTo(Detail.getStartDate()) >= 0 && day.compareTo(Detail.getEndDate()) <= 0) {
                    investorDetailDays = DateUtils.getDistanceOfTwoDate(Detail.getStartDate(), day);
                } else if (day.compareTo(Detail.getStartDate()) > 0 && day.compareTo(Detail.getEndDate()) > 0) {
                    investorDetailDays = DateUtils.getDistanceOfTwoDate(Detail.getStartDate(), Detail.getEndDate());
                }
                if ("2".equals(finServiceOrder.getCalculationMethod()))// 本金加上期利息
                {
                    negotiatedAmount2 = negotiatedAmount2 + customerInterestTotal;
                }
                Double interest = NumberUtils.mul(NumberUtils.div(NumberUtils.mul(negotiatedAmount2, investorDetailRatio), investorYearDays), investorDetailDays);
                customerInterestTotal = NumberUtils.add(customerInterestTotal, interest);
//				Detail.setInterest(Double.valueOf(String.format("%.2f", interest)));
            }
        }
        Double totalDays = DateUtils.getDistanceOfTwoDate(tfinancingServiceOrderDetailList.get(0).getStartDate(), day);//合计天数
        finServiceOrder.setInvestorRepaymentDate(day);
        finServiceOrder.setInvestorDays(totalDays.longValue());
        finServiceOrder.setInvestorTotalInterest(Double.valueOf(String.format("%.2f", customerInterestTotal)));
        finServiceOrder.setInvestorTotalPrincipalInterest(Double.valueOf(String.format("%.2f", NumberUtils.add(customerInterestTotal, finServiceOrder.getCarTotalAmount()))));
        finServiceOrderService.save(finServiceOrder);//更新还款到资方信息
        //获得币种
        ServiceOrderDetail serviceOrderDetail = new ServiceOrderDetail();
        serviceOrderDetail.setFrameNumber(finServiceOrder.getFrameNumber());
        ServiceOrderDetail serviceOrderDetail1 = serviceOrderDetailDao.findList(serviceOrderDetail).get(0);
        //获得了车架号对应的订单
        ServiceOrder serviceOrder = serviceOrderService.get(new ServiceOrder(serviceOrderDetail1.getServiceOrderId().getServiceOrderId()));

        Tap tap = new Tap();
        tap.setSupplierId(finServiceOrder.getInvestorId());
        tap.setSupplier(new Supplier(finServiceOrder.getInvestorId()));//资方
        tap.setDate(new Date());//日期
        tap.setStatus1("1"); //默认待生效
        tap.setServiceOrderId(serviceOrder.getServiceOrderId());
        tap.setCurrency(serviceOrder.getCurrency());//币种
        tap.setAmount(NumberUtils.add(finServiceOrder.getCarTotalAmount(), Double.valueOf(String.format("%.2f", customerInterestTotal))));
        tap.setParentBillType("finServiceOrder001");
        tap.setParentBillCode(finServiceOrder.getFinancingServiceOrderId());
        tap.setRemarks(finServiceOrder.getRemarks());

        //生成字表
        List < TapDetail > tapDetailList = ListUtils.newArrayList();
        for (int i = 0; i < 2; i++) {
            TapDetail tapDetail = new TapDetail();
            tapDetail.setBrand(serviceOrderDetail1.getBrand());
            tapDetail.setArea(serviceOrderDetail1.getArea());
            tapDetail.setModel(serviceOrderDetail1.getModel());
            tapDetail.setFrameNumber(serviceOrderDetail1.getFrameNumber());
            tapDetail.setCarId(serviceOrderDetail1.getCarId());
            tapDetail.setCar(new Tcar(serviceOrderDetail1.getCarId()));
            tapDetail.setRowNumber(serviceOrderDetail1.getRowNumber());
            if (i == 0) {
                if ("1".equals(finServiceOrder.getFinancingMethod())) {
                    tapDetail.setExpenseItem(AccountType.ZRBJ.getCode());
                    tapDetail.setFixedExpense(new FixedExpense(AccountType.ZRBJ.getCode()));
                } else if ("2".equals(finServiceOrder.getFinancingMethod())) {
                    tapDetail.setExpenseItem(AccountType.KRBJ.getCode());
                    tapDetail.setFixedExpense(new FixedExpense(AccountType.KRBJ.getCode()));
                }
                tapDetail.setApAmount(finServiceOrder.getCarTotalAmount());
            } else if (i == 1) {
                if ("1".equals(finServiceOrder.getFinancingMethod())) {
                    tapDetail.setExpenseItem(AccountType.ZRLX.getCode());
                    tapDetail.setFixedExpense(new FixedExpense(AccountType.ZRLX.getCode()));
                } else if ("2".equals(finServiceOrder.getFinancingMethod())) {
                    tapDetail.setExpenseItem(AccountType.KRLX.getCode());
                    tapDetail.setFixedExpense(new FixedExpense(AccountType.KRLX.getCode()));
                }
                tapDetail.setApAmount(Double.valueOf(String.format("%.2f", customerInterestTotal)));
            }
            tapDetailList.add(tapDetail);
        }
        tap.setTapDetailList(tapDetailList);
        tapService.save(tap);
        // todo 生成客户应收
        return renderResult(Global.TRUE, text("还款到资方保存成功！"));
    }


    /**
     * 通过资方和融资方式获得融资方案	 *
     */
    @RequestMapping(value = "getTaxNameByInvestorName")
    @ResponseBody
    public List < InvestorFinancialInfo > getTaxNameByInvestorName(@RequestParam("investorName") String investorName, @RequestParam("financingMethod") String financingMethod) {
        InvestorFinancialInfo investorFinancialInfo = new InvestorFinancialInfo();
        investorFinancialInfo.setInvestorName(investorName);
        investorFinancialInfo.setFinancingMethod(financingMethod);
        investorFinancialInfo.setFinancingType("4"); // 国内融资
        List < InvestorFinancialInfo > list = investorFinancialInfoService.findList(investorFinancialInfo);
        return list;
    }

    /**
     * 预收生成
     */
    @RequiresPermissions("financial:billnegotiated:billNegotiated:edit")
    @PostMapping(value = "saveFinAdFrom")
    @ResponseBody
    @Transactional(readOnly = false)
    public String saveFinAdFrom(FinServiceOrder finServiceOrder) {
        ServiceOrderDetail serviceOrderDetail = new ServiceOrderDetail();
        serviceOrderDetail.setFrameNumber(finServiceOrder.getFrameNumber());
        ServiceOrderDetail serviceOrderDetail1 = serviceOrderDetailDao.findList(serviceOrderDetail).get(0);
        //获得了车架号对应的订单
        ServiceOrder serviceOrder = serviceOrderService.get(new ServiceOrder(serviceOrderDetail1.getServiceOrderId().getServiceOrderId()));
        if ("releasecar002".equals(finServiceOrder.getErpRecordType()))//生成预收款
        {
            TadvancesReceived t = new TadvancesReceived();
            t.setParentBillCode(finServiceOrder.getFinancingServiceOrderId());
            t.setRowNumber(Long.valueOf(finServiceOrder.getGridRowId()));
            List < TadvancesReceived > collect = tadvancesReceivedService.findList(t).stream().filter(ele -> !"5".equals(ele.getStatus1())).collect(Collectors.toList());
            if (collect.size() == 0) {
                TadvancesReceived tadvancesReceived = new TadvancesReceived();
                tadvancesReceived.setRowNumber(Long.valueOf(finServiceOrder.getGridRowId()));
                tadvancesReceived.setCustomerId(finServiceOrder.getCustomerId());
                tadvancesReceived.setCustomer(finServiceOrder.getCustomer());
                tadvancesReceived.setDate(new Date());
                tadvancesReceived.setStatus1("1");
                tadvancesReceived.setServiceOrderId(serviceOrder.getServiceOrderId());
                tadvancesReceived.setServiceOrder(serviceOrder);
                tadvancesReceived.setCurrency(serviceOrder.getCurrency());
                tadvancesReceived.setAdvancesReceivedBalance(finServiceOrder.getMoney());
                tadvancesReceived.setEstimatedReceivedAmount(finServiceOrder.getMoney());
                tadvancesReceived.setParentBillType("finServiceOrder001");
                tadvancesReceived.setParentBillCode(finServiceOrder.getFinancingServiceOrderId());
                List < TadvancesReceivedEstimated > tadvancesReceivedEstimatedList = ListUtils.newArrayList();
                TadvancesReceivedEstimated tadvancesReceivedEstimated = new TadvancesReceivedEstimated();
                tadvancesReceivedEstimated.setFrameNumber(finServiceOrder.getFrameNumber());
                if ("1".equals(finServiceOrder.getFinancingMethod())) {
                    tadvancesReceivedEstimated.setAdvancesReceivedType("ITM00000024");//展融保证金
                } else if ("2".equals(finServiceOrder.getFinancingMethod())) {
                    tadvancesReceivedEstimated.setAdvancesReceivedType("ITM00000020");//展融保证金
                }
                tadvancesReceivedEstimated.setCarName1(serviceOrderDetail1.getTcar().getCarName());
                tadvancesReceivedEstimated.setEstimatedReceivedAmount(finServiceOrder.getMoney());
                tadvancesReceivedEstimated.setRowNumber(serviceOrderDetail1.getRowNumber());
                tadvancesReceivedEstimatedList.add(tadvancesReceivedEstimated);
                tadvancesReceived.setTadvancesReceivedEstimatedList(tadvancesReceivedEstimatedList);
                tadvancesReceivedService.save(tadvancesReceived);
                return renderResult(Global.TRUE, text("保证金预收成功！"));
            } else {
                return renderResult(Global.FALSE, text("保证金已预收请不要重复预收！！！"));
            }
            // todo 生成客户应收

        }
        if ("inboundorder001".equals(finServiceOrder.getErpRecordType()))//生成预付款
        {
            Tprepayment t = new Tprepayment();
            t.setParentBillCode(finServiceOrder.getFinancingServiceOrderId());
            t.setRowNumber(Integer.valueOf(finServiceOrder.getGridRowId()));
            List < Tprepayment > collect = tprepaymentService.findList(t).stream().filter(ele -> !"5".equals(ele.getStatus1())).collect(Collectors.toList());
            if (collect.size() == 0) {
                Tprepayment tprepayment = new Tprepayment();
                tprepayment.setRowNumber(Integer.valueOf(finServiceOrder.getGridRowId()));
                tprepayment.setSupplierId(finServiceOrder.getInvestorId());
                tprepayment.setDate(new Date());
                tprepayment.setStatus1("1");
                tprepayment.setServiceOrderId(serviceOrder.getServiceOrderId());
                tprepayment.setCurrency(serviceOrder.getCurrency());
                tprepayment.setPrepaymentType("1");
                tprepayment.setPrepaymentBalance(finServiceOrder.getMoney());
                tprepayment.setEstimatedPaymentAmount(finServiceOrder.getMoney());
                tprepayment.setParentBillType("finServiceOrder001");
                tprepayment.setParentBillCode(finServiceOrder.getFinancingServiceOrderId());
                List < TadvancesReceivedEstimated > tadvancesReceivedEstimatedList = ListUtils.newArrayList();
                List < TprepaymentEstimated > tprepaymentEstimatedList = ListUtils.newArrayList();
                TprepaymentEstimated tprepaymentEstimated = new TprepaymentEstimated();
                tprepaymentEstimated.setFrameNumber(finServiceOrder.getFrameNumber());
                if ("1".equals(finServiceOrder.getFinancingMethod())) {
                    tprepaymentEstimated.setPrepaymentType("ITM00000024");//展融保证金
                } else if ("2".equals(finServiceOrder.getFinancingMethod())) {
                    tprepaymentEstimated.setPrepaymentType("ITM00000020");//库融保证金
                }
                tprepaymentEstimated.setCarName(serviceOrderDetail1.getTcar().getCarName());
                tprepaymentEstimated.setEstimatedPaymentAmount(finServiceOrder.getMoney());
                tprepaymentEstimated.setRowNumber(serviceOrderDetail1.getRowNumber());
                tprepaymentEstimatedList.add(tprepaymentEstimated);
                tprepayment.setTprepaymentEstimatedList(tprepaymentEstimatedList);
                tprepaymentService.save(tprepayment);
                // todo 生成客户应收
                return renderResult(Global.TRUE, text("保证金预付成功！"));
            } else {
                return renderResult(Global.FALSE, text("保证金已预付请不要重复预付！！！"));
            }
        }
        // todo 生成客户应收
        return "";
    }

    /**
     * 根据单据类型和编号，实现详情页面跳转
     *
     * @param parentBillType 前置单据类型
     * @param parentBillCode 前置单据编号
     * @return 单据编号
     */
    @RequestMapping(value = "forwardByBillCodeAndType")
    public String forwardByBillCodeAndType(@RequestParam("parentBillType") String parentBillType,
                                           @RequestParam("parentBillCode") String parentBillCode) {
        BillStatusEnum billStatusEnum = BillStatusEnum.valueOf(parentBillType);
        String code = "redirect:" + billStatusEnum.getPath() + parentBillCode;
        return code;
    }

}
